package com.kung.qvs.ui.main;

import static com.kung.qvs.serialusb.UsbPrinter.ACTION_USB_PERMISSION;
import static com.kung.qvs.utils.Constants.URL_PRINT;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetFileDescriptor;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.aill.androidserialport.SerialPort;
import com.jackiepenghe.serialportlibrary.OnSerialPortDataChangedListener;
import com.jackiepenghe.serialportlibrary.SerialPortManager;
import com.kung.qvs.BR;
import com.kung.qvs.R;
import com.kung.qvs.app.AppApplication;
import com.kung.qvs.app.AppViewModelFactory;
import com.kung.qvs.databinding.ActivityHomeBinding;
import com.kung.qvs.entity.PrintDataBean;
import com.kung.qvs.serialusb.ESCUtil;
import com.kung.qvs.serialusb.UsbPrinter;
import com.kung.qvs.ui.widget.ConformDialog;
import com.kung.qvs.utils.CommonUtils;
import com.kung.qvs.utils.Constants;
import com.kung.qvs.utils.HexUtil;
import com.kung.qvs.utils.ScanKeyManager;
import com.kung.qvs.utils.SerialManager;
import com.kung.qvs.utils.SoftKeyBoardListener;
import com.kung.qvs.utils.usbprinter.USBUtil;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseActivity;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import pub.devrel.easypermissions.EasyPermissions;

public class HomeActivity extends BaseActivity<ActivityHomeBinding,HomeViewModel> implements EasyPermissions.PermissionCallbacks{

    private static String TAG = HomeActivity.class.getSimpleName();
    private static HomeActivity mHomeActivity;

    private NavController navController;
    private KungViewModel kungViewModel;

    public static final int REC_DATA = 2;
    public static final int CONNECTED_DEVICE_NAME = 4;
    public static final int BT_TOAST = 5;
    public static final int MAIN_TOAST = 6;

    public static final int REQUEST_CODE_PERMISSION_LOCATION = 5;
    public static final int REQUEST_CODE_OPEN_BLUETOOTH = 6;
    public static final int REQUEST_CODE_PERMISSION_STORAGE = 7;
    // 标志字符串常量
    public static final String DEVICE_NAME = "device name";
    public static final String TOAST = "toast";

    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION};

    String[] perms2 = {Manifest.permission.READ_PHONE_STATE};

    private String deviceType = "1";  //当前操作设备  1蓝牙秤，2打印机


    Timer timer = new Timer(true);
//    Timer timerHeartTask = new Timer(true);

    Timer timerUpload = new Timer(true);

    private String serialNo = "";   //设备序列号
    private ConnectedThread mConnectedThread;

    private UsbPrinter usbPrinter;//USB打印
//    TSCUSBActivity TscUSB = new TSCUSBActivity();
    private UsbDevice mUsbDevice;

    private boolean isBlePrint = false; //true 蓝牙连接打印机；false USB串口打印连接
    private boolean isTSC = true;   //tsc 指令 ;  esc

    public static final String ACTION_USB_STATE = "android.hardware.usb.action.USB_STATE";

    //音频播放器对象
    private MediaPlayer mediaPlayer;

    private ScanKeyManager scanKeyManager;  //https://www.jianshu.com/p/5c1bf3e968e6    Android外接USB扫码枪
    /*是否是输入状态（输入时扫码监听不拦截）*/
    private boolean isInput = false;

    //记录上一次扫描的工人卡号
    private String lastWorkerCode = "";
    //上一次扫描工人卡号时间
    private long lastWorkerCodeTime = 0;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_home;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public HomeViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(HomeViewModel.class);
    }

    @Override
    public void initParam() {
        super.initParam();
    }

    @Override
    public void initData() {
        super.initData();
        AppApplication.homeActivity = new WeakReference<HomeActivity>(this);
        mHomeActivity = this;
        navController = Navigation.findNavController(this, R.id.nav_host_fragment);

        kungViewModel = new ViewModelProvider(this).get(KungViewModel.class);

        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, "App正常运行需要存储权限、媒体权限", 1, perms);
        }

        if (isBlePrint) {
            // 查看请求打开蓝牙
        } else {
            // 注册广播监听usb设备
            IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(ACTION_USB_STATE);
            registerReceiver(mUsbDeviceReceiver, filter);

            // 初始化usb串口的连接
            if (isTSC) {
                USBUtil.getInstance().init(getApplication());
            } else {
                usbPrinter = UsbPrinter.getInstance();
                usbPrinter.initPrinter(mHomeActivity);
            }
        }
        //延时1秒执行
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //初始化串口
                aotoConnectBluetoothDevice();
                try {
                    openSerialCardRead();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }, 1500);

        SerialPortManager.setOnSerialPortDataChangedListener(new OnSerialPortDataChangedListener() {
            @Override
            public void serialPortDataReceived(byte[] data, int size) {
                //转换为字符串
                if (data.length ==22) {
                    byte[] temp = Arrays.copyOfRange(data, 5, 10);
                    String temp_data = new String(temp);
                    //解析读取到的数据
                    //不同卡号，10秒内不允许读取
                    if (System.currentTimeMillis() - lastWorkerCodeTime < 1000 * 6) {
                        //如果是同一个工人卡号，且时间间隔小于15秒，则不处理
                        ToastUtils.showShort("请勿频繁刷卡");
                        return;
                    }

                    if (temp_data.equals(lastWorkerCode) && System.currentTimeMillis() - lastWorkerCodeTime < 1000 * 15) {
                        //如果是同一个工人卡号，且时间间隔小于15秒，则不处理
                        ToastUtils.showShort("请勿频繁刷卡");
                        return;
                    }

                    lastWorkerCode = temp_data;
                    lastWorkerCodeTime = System.currentTimeMillis();
                    kungViewModel.setmSearchWorkerCode(temp_data);
                    //根据卡号查询工人信息
                }
            }
        });

        //拦截扫码器回调,获取扫码内容
        scanKeyManager = new ScanKeyManager(new ScanKeyManager.OnScanValueListener() {
            @Override
            public void onScanValue(String value) {
                //根据扫码内容查询粽子品类
                kungViewModel.setmScanProductCode(value);
            }
        });
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.uc.eventStopTimerCommond.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {


                timerUpload.cancel();
                ToastUtils.showShort("同步上传数据结束");
            }
        });

        viewModel.uc.eventNoticeFinishUpload.observe(this, new Observer() {
            @Override
            public void onChanged(Object o) {
                kungViewModel.setmIsFinishUpload(true);
            }
        });
    }

    /**
     * 自动连接蓝牙任务
     */
    private void aotoConnectBluetoothDevice() {
        //定时任务，连接蓝牙秤
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                if (!SerialManager.getInstance().isOpened()) {
                    SerialManager.getInstance().openSerial("/dev/ttyS1", 9600);
                    // 开启已连接线程
                    if (mConnectedThread == null) {
                        mConnectedThread = new ConnectedThread(SerialManager.getInstance().getSerialPort());
                        mConnectedThread.start();
                    }
                }

                if (isBlePrint) {
//                    if (!StringUtils.isTrimEmpty(viewModel.getBtMacWeigh(Constants.DEVICE_TYPE2)) && !kungViewModel.getmIsBlePrinterConnect().getValue()) {
//                        //如果蓝牙已保存，且未连接，则尝试连接
//                        ConnectBTDevicePrint(null);
//                    }
                } else {
                    //显示USB打印机连接状态
//                    if (usbPrinter != null && usbPrinter.isConnected()) {
//                        if (!kungViewModel.getmIsBlePrinterConnect().getValue()) {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    kungViewModel.getmIsBlePrinterConnect().setValue(true);
//                                }
//                            });
//                        }
//                    }
                    if (isTSC && USBUtil.getInstance().isConnected()) {
                        if (!kungViewModel.getmIsBlePrinterConnect().getValue()) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    kungViewModel.getmIsBlePrinterConnect().setValue(true);
                                }
                            });
                        }
                    }
                }

                if (!EasyPermissions.hasPermissions(mHomeActivity, perms2)) {
                    EasyPermissions.requestPermissions(mHomeActivity, "App正常运行需要电话权限", 1, perms2);
                } else {
                    serialNo = CommonUtils.getSerialNum();
                    viewModel.setHardWareCode(serialNo);
                    kungViewModel.setmIsHasHardWareCode(true);
                    viewModel.doAddDevice(serialNo);
                }
            }
        },100,2000);
        //5分钟一次心跳任务
//        timerHeartTask.scheduleAtFixedRate(new TimerTask() {
//            @Override
//            public void run() {
//                viewModel.doUpdateStatus();
//            }
//        },1000,300000);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        if (EasyPermissions.hasPermissions(this, perms2)) {
            serialNo = CommonUtils.getSerialNum();
            viewModel.setHardWareCode(serialNo);
            kungViewModel.setmIsHasHardWareCode(true);
            viewModel.doAddDevice(serialNo);
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

    // 用于从线程获取信息的Handler对象
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler(){
        String msgResult;
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REC_DATA:
                    try{
                        msgResult = (String) msg.obj;
                        //进行解密
                        doDealDecryptionWeight(msgResult);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    break;
            }
        }
    };

    /**
     * 对接收到的重量进行解密
     * @param rec_data
     */
    private void doDealDecryptionWeight(String rec_data) throws Exception {
//        rec_data = "023165097EAFECDF1648B9B75485FA3B6A598EFFB6598EFF3C6FA698C9A203";
        if (StringUtils.isTrimEmpty(rec_data) || rec_data.length() != 31 * 2) {
            return;
        }
        byte[] bytes = HexUtil.hexStringToBytes(rec_data);  //长度31

        int data_A = bytes[1] & 0xff;
        int data_B = bytes[29] & 0xff;

        int startIndex = 0;
        int result = 0;
        //毛重索引 2-10
        //皮重    11-19
        //净重    20-28
        String weight_jz = "";  //净重
        startIndex = 20;
        for (int i = 1; i < 9; i++) {
            result = int2Bytes(bytes[startIndex + i] ^ data_B)[0];
            result = int2Bytes(result - i * data_A)[0];
            result = int2Bytes(result - 0xAA)[0];
            weight_jz += (char) result;
        }

        if (!StringUtils.isTrimEmpty(weight_jz)) {
            weight_jz = weight_jz.trim();
            kungViewModel.sendWeight(weight_jz);
        }
    }

    public static byte[] int2Bytes(int integer) {
        byte[] bytes=new byte[4];
        bytes[3]= (byte) (integer>>24);
        bytes[2]= (byte) (integer>>16);
        bytes[1]= (byte) (integer>>8);
        bytes[0]= (byte) integer;

        return bytes;
    }

    private Fragment getCFragment(){
        Log.d(TAG,"Primary="+getSupportFragmentManager().getPrimaryNavigationFragment());//主要导航Fragment
        Log.d(TAG,"Fragment by id ="+getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment));
        Log.d(TAG,"Fragment="+getSupportFragmentManager().getFragments().get(0));
        return   getSupportFragmentManager().findFragmentById(R.id.nav_host_fragment);
    }

    private Fragment getPrimaryFragment(Class<?> clazz) {
        for (Fragment fragment : getCFragment().getChildFragmentManager().getFragments())         {
            if (clazz.isAssignableFrom(fragment.getClass())) {
                return fragment;
            }
        }
        return null;
    }

    /**
     * 自动连接蓝牙任务
     */
    public void aotoUploadTrashRecord() {
        if (timerUpload == null) {
            timerUpload = new Timer(true);
        }

        timerUpload.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                LogUtil.i("gkm-test-uploadtimer");
                viewModel.doAddWasReport();
            }
        },500,1000);
    }

    private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            mUsbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false) && mUsbDevice != null) {

                    } else {
                        ToastUtils.showShort( "USB设备请求被拒绝");
                        kungViewModel.getmIsBlePrinterConnect().setValue(false);
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                if (mUsbDevice != null) {
                    ToastUtils.showShort( "有设备拔出");
                    kungViewModel.getmIsBlePrinterConnect().setValue(false);
                }
            } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                ToastUtils.showShort( "有设备插入");

                usbUtil = USBUtil.getInstance();
                if (mUsbDevice == null) {
                    mUsbDevice = usbUtil.getUsbDevice(19267, 13624);
                }

                if (mUsbDevice != null) {
                    usbUtil.openPort(mUsbDevice);
                }
            } else if (ACTION_USB_STATE.equals(action)) {

                boolean connected = true;
                try {
                    /**  true - USB连接；false - USB未连接 或 电源充电  */
                    connected = intent.getBooleanExtra("connected", false);
//                    ToastUtils.showShort( "有设备" + connected);
//                    kungViewModel.getmIsBlePrinterConnect().setValue(connected);
                    usbUtil = USBUtil.getInstance();
                    if (mUsbDevice == null) {
                        mUsbDevice = usbUtil.getUsbDevice(19267, 13624);
                    }

                    if (mUsbDevice != null) {
                        usbUtil.openPort(mUsbDevice);
                    }

                    /** true - USB传输文件模式  */
//                    boolean function_mtp = intent.getBooleanExtra(USB_FUNCTION_MTP, false);
//                    /** true - USB传输图片模式  */
//                    boolean function_ptp = intent.getBooleanExtra(USB_FUNCTION_PTP, false);
//                    /** true - adb模式（USB调试） */
//                    boolean function_adb = intent.getBooleanExtra(USB_FUNCTION_ADB , false);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 连接串口读卡器
     */
    public void openSerialCardRead() throws IOException {
        if (SerialPortManager.isOpened()) {
            ToastUtils.showShort("串口已打开!");
            return;
        }
        boolean open = SerialPortManager.openSerialPort("/dev/ttyS2", 9600);
        if (open) {
            ToastUtils.showShort("串口打开成功!");
        } else {
            ToastUtils.showShort("串口打开失败!");
        }
    }

    /*监听键盘事件,除了返回事件都将它拦截,使用我们自定义的拦截器处理该事件*/
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() != KeyEvent.KEYCODE_BACK && !isInput) {
            scanKeyManager.analysisKeyEvent(event);
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    /**
     * 监听软件盘是否弹起
     */
    private void onKeyBoardListener() {
        SoftKeyBoardListener.setListener(this, new SoftKeyBoardListener.OnSoftKeyBoardChangeListener() {
            @Override
            public void keyBoardShow(int height) {
                Log.e("软键盘", "键盘显示 高度" + height);
                isInput = true;
            }

            @Override
            public void keyBoardHide(int height) {
                Log.e("软键盘", "键盘隐藏 高度" + height);
                isInput = false;
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            timer.cancel();
//            timerHeartTask.cancel();
            timerUpload.cancel();
            SerialPortManager.closeSerialPort();
            stopAudio();
//            if (usbPrinter != null) {
//                usbPrinter.close();
//            }

            kungViewModel.getmIsBleBalanceConnect().setValue(false);

            if (mUsbDeviceReceiver != null) {
                unregisterReceiver(mUsbDeviceReceiver);
            }

            if (SerialManager.getInstance().isOpened()) {
                SerialManager.getInstance().closeSerial();
            }
            usbUtil.closeport(500);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_OPEN_BLUETOOTH:
                String[] perms = {Manifest.permission.BLUETOOTH,
                        Manifest.permission.BLUETOOTH_ADMIN,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION};
                if (!EasyPermissions.hasPermissions(this, perms)) {
                    EasyPermissions.requestPermissions(this, "App正常运行需要存储权限、蓝牙权限", 1, perms);
                }
                break;
        }
    }

    /**
     * 已连接的相关处理线程
     */
    private class ConnectedThread extends Thread {
        private final SerialPort serialPort;
        private final InputStream mInputStream;
        private final OutputStream mOutputStream;

        public ConnectedThread(SerialPort socket) {
            serialPort = socket;
            InputStream is;
            OutputStream os;
            // 获取输入输出流
            is = socket.getInputStream();
            os = socket.getOutputStream();

            mInputStream = is;
            mOutputStream = os;
        }

        public void run() {
            byte[] buffer = new byte[1024];
            DataInputStream in = new DataInputStream(mInputStream);
            // 监听输入流以备获取数据
            while (true) {
                
                try {
                    if (mInputStream.available() > 0) {
                        //当接收到数据时，sleep 500毫秒（sleep时间自己把握）
                        Thread.sleep(50);
                        //sleep过后，再读取数据，基本上都是完整的数据
//                        buffer = new byte[mInputStream.available()];
//                        size = mInputStream.read(buffer);
                        int l;
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        while ((l = in.read(buffer)) != -1) {
                            out.write(buffer, 0, l);
                            break;
                        }
                        //转换为16进制字符串-健坤专用，别的称可能不支持
                        String temp_data = HexUtil.formatHexString(out.toByteArray(), false).toUpperCase();
                        mHandler.obtainMessage(REC_DATA, temp_data).sendToTarget();
                    }
                } catch (IOException | InterruptedException e) {
                    Log.e(TAG, "connection break", e);
                    break;
                }
                try {
                    //线程睡眠20ms以避免过于频繁工作  50ms->20ms 2017.12.2
                    //导致UI处理发回的数据不及时而阻塞
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    public boolean doPrintContent(PrintDataBean printDataBean, String printModel) {
        if (!isBlePrint) {
            //使用USB打印
            doPrintContentUSB(printDataBean, printModel);
            return false;
        }
        return true;
    }

    /**
     * USB串口打印
     */
    private void doPrintContentUSB(PrintDataBean printDataBean, String printModel) {
        // 设置加粗
        doPrintUsbTsc(printDataBean, printModel);
    }

    private USBUtil usbUtil;

    /**
     * 打印
     */
    int startX = 93;
    int startY = 275;
    private void doPrintUsbTsc(PrintDataBean printDataBean, String printModel){
        usbUtil = USBUtil.getInstance();
        if (mUsbDevice == null) {
            mUsbDevice = usbUtil.getUsbDevice(19267, 13624);
        }
        //其实高度坐标
        int startY2 = 65;
        //间隔距离
        int interval = 35;
        String s;
        if (mUsbDevice != null && usbUtil.openPort(mUsbDevice)) {

//            s = "INTIALPRINTER\n" +
//                    "SIZE 54 mm,38 mm\n" +
//                    "GAP 2 mm,0 mm\n" +
//                    "DIRECTION 1 \n" +
//                    "CLS\n";
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            s = "BOX 0,60,380,280,3\n"; //x1,y1,x2,y2,宽度  ：矩形
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            s = "TEXT 1,5,\"3\",0,1.3,1.3,\"" + printDataBean.getCompanyName() + "\"\n"; //公司名称
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"产品： " + printDataBean.getProductName() + "\"\n"; //Size#
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//            startY2 += interval;
//            if (!StringUtils.isTrimEmpty(printDataBean.getListing()) && printDataBean.getListing().equals("1")) {
//                s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"挂牌： 是\"\n"; //是否挂牌
//                usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//            } else {
//                s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"挂牌： 否\"\n"; //是否挂牌
//                usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//            }
//
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"重量： " + printDataBean.getWeight() + getString(R.string.unit_kg) + "\"\n"; //产品型号
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"数量： " + printDataBean.getAmount() + "\"\n"; //产品名称
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"工人： " + printDataBean.getWorkName() + " - " + printDataBean.getWorkId() + "\"\n"; //产品名称
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"日期: " + printDataBean.getFcdate() + "\"\n"; //批号
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"编号: " + printDataBean.getPrintCode() + "\"\n"; //批号
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            //走纸
//            startY2 += interval;
//            startY2 += interval;
//            s = "TEXT 5," + startY2 + ",\"2\",0,1,1,\"" + printDataBean.getPrintCode() + "\"\n"; //批号
//            usbUtil.sendMessage(s.getBytes(StandardCharsets.UTF_8));
//
//            usbUtil.sendMessage(printlabel(1,1));

            String msg = "";
            try {
                // 设置加粗
                usbUtil.sendMessage(ESCUtil.boldOn());
                // 文字大小
                usbUtil.sendMessage(ESCUtil.setTextSize(2));
                // 设置文字居中
                usbUtil.sendMessage(ESCUtil.alignCenter());
                msg = printDataBean.getCompanyName();
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                // 取消加粗
                usbUtil.sendMessage(ESCUtil.boldOff());
                //文字大小
                usbUtil.sendMessage(ESCUtil.setTextSize(0));
                msg = "----------------------------------------------";
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                //设置文字居左边
                usbUtil.sendMessage(ESCUtil.alignLeft());
                msg = "产品： " + printDataBean.getProductName();
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));

//                if (!StringUtils.isTrimEmpty(printDataBean.getListing()) && printDataBean.getListing().equals("1")) {
//                    msg = "挂牌： 是\n"; //是否挂牌
//                } else {
//                    msg = "挂牌： 否\n"; //是否挂牌
//                }
//                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));

                msg = "重量： " + printDataBean.getWeight() + getString(R.string.unit_kg) + "\n";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));

                msg = "数量： " + printDataBean.getAmount() + "\n";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));

                msg = "工人： " + printDataBean.getWorkName() + " - " + printDataBean.getWorkId() + "\n";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                msg = "日期: " + printDataBean.getFcdate() + "\n";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                msg = "编号: " + printDataBean.getPrintCode() + "\n";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                msg = "----------------------------------------------";
                usbUtil.sendMessage(msg.getBytes(StandardCharsets.UTF_8));
                //走纸
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                usbUtil.sendMessage("\n".getBytes(StandardCharsets.UTF_8));
                // 切纸
                usbUtil.sendMessage(ESCUtil.cutter());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public byte[] setup(int width, int height, int speed, int density, int sensor, int sensor_distance, int sensor_offset) {
        String message = "";
        String size = "SIZE " + width + " mm" + ", " + height + " mm";
        String speed_value = "SPEED " + speed;
        String density_value = "DENSITY " + density;
        String sensor_value = "";
        if (sensor == 0) {
            sensor_value = "GAP " + sensor_distance + " mm" + ", " + sensor_offset + " mm";
        } else if (sensor == 1) {
            sensor_value = "BLINE " + sensor_distance + " mm" + ", " + sensor_offset + " mm";
        }

        message = size + "\r\n" + speed_value + "\r\n" + density_value + "\r\n" + sensor_value + "\r\n";
        return message.getBytes();
    }

    public byte[] clearbuffer() {
        String message = "CLS\r\n";
        return message.getBytes();
    }


    public byte[] barcode(int x, int y, String type, int height, int human_readable, int rotation, int narrow, int wide, String string) {
        String message = "";
        String barcode = "BARCODE ";
        String position = x + "," + y;
        String mode = "\"" + type + "\"";
        String height_value = "" + height;
        String human_value = "" + human_readable;
        String rota = "" + rotation;
        String narrow_value = "" + narrow;
        String wide_value = "" + wide;
        String string_value = "\"" + string + "\"";
        message = barcode + position + " ," + mode + " ," + height_value + " ," + human_value + " ," + rota + " ," + narrow_value + " ," + wide_value + " ," + string_value + "\r\n";
        return message.getBytes();
    }

    public byte[] printlabel(int quantity, int copy) {
        String message = "";
        message = "PRINT " + quantity + ", " + copy + "\r\n";
        return message.getBytes();
    }

    public void funPlayAudioRecSuccess() {
        playAudio(R.raw.upload_success);
    }

    public void funPlayAudioRecNoWorker() {
        playAudio(R.raw.worker_no);
    }

    //播放音频
    private void playAudio(int rawId) {
        try {
            if (mediaPlayer == null) {
                mediaPlayer = new MediaPlayer();
            }
            Context context = getApplicationContext();
            Resources resources = context.getResources();
            AssetFileDescriptor rawFile = resources.openRawResourceFd(rawId);
            mediaPlayer.reset();
            mediaPlayer.setDataSource(rawFile.getFileDescriptor(), rawFile.getStartOffset(), rawFile.getLength());
            rawFile.close();
            mediaPlayer.prepare();
            mediaPlayer.start();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        }
    }

    //停止播放音频
    private void stopAudio() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        }
    }

    private long exitTime = 0;

    @Override
    public void onBackPressed() {
        //判断当前是否为首页
        if (navController.getCurrentDestination().getId() == R.id.mainFrag) {
            //连续点击两次退出
            if (System.currentTimeMillis() - exitTime > 2000) {
                ToastUtils.showShort("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
        } else {
            super.onBackPressed();
        }
    }
}
